package com.sali.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sali.mapper.CourseCategoryMapper;
import com.sali.pojo.CourseCategory;
import com.sali.service.ICourseCategoryService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Description: 查询无限级子目录
 * Version: 1.0
 * Create Date Time: 2022/3/7 9:36 下午.
 * Update Date Time:
 *
 * @see
 */
@Service
@Log4j2
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements ICourseCategoryService {

    @Override
    public List<CourseCategory> findCategoriesTree() {

        // 查询表中所有数据
        List<CourseCategory> allList = this.list();

        // 找到所有根节点
        List<CourseCategory> rootList = allList.stream().filter(courseCategory -> courseCategory.getPid().equals(0)).collect(Collectors.toList());

        // 查询所有的非根节点
        List<CourseCategory> subList = allList.stream().filter(courseCategory -> !courseCategory.getPid().equals(0)).collect(Collectors.toList());

        // 循环rootList去subList中找child
        rootList = rootList.stream().peek(root -> busorts(root, subList)).collect(Collectors.toList());

        return rootList;
    }

    /**
     * description: 给root赋值对应的subList
     *
     * @author: zhang hang
     **/
    private void busorts(CourseCategory root, List<CourseCategory> subList) {
        // 判断根节点id和子节点pid是否相等
        List<CourseCategory> childrenList = subList.stream().filter(category -> category.getPid().equals(root.getId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(childrenList)) {
            root.setChildrenList(childrenList);
            childrenList.forEach(child -> busorts(child, subList));
        }
    }

}
